package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/iris-contrib/middleware/cors"
	"github.com/joho/godotenv"
	"github.com/kataras/golog"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"

	"im/common"
	"im/crons"
	"im/dao"
	"im/dao/es"
	"im/router"
	"im/service/orm"
	"im/service/push"
)

func main() {
	app := iris.New()
	app.Use(recover.New())
	app.Use(logger.New())
	// 优雅关闭
	iris.RegisterOnInterrupt(func() {
		timeout := 5 * time.Second
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		defer cancel()
		app.Shutdown(ctx)
	})
	app.ConfigureHost(func(h *iris.Supervisor) {
		h.RegisterOnShutdown(func() {
			fmt.Println("服务已关闭")
		})
	})

	// 环境配置
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	crs := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
		AllowedMethods:   []string{"PUT", "PATCH", "GET", "POST", "OPTIONS", "DELETE"},
		AllowedHeaders:   []string{"*"},
		ExposedHeaders:   []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
		AllowCredentials: true,
	})
	app.Use(crs)
	// 数据库结构同步
	orm.SyncDB()
	dao.InitAll()
	// es生成mapping
	err = es.Init()
	if err != nil {
		panic(err)
	}
	push.Init()
	crons.Run()

	// 静态资源
	app.RegisterView(iris.HTML("./public", ".html"))
	app.HandleDir("/static", "./static")
	// docs
	if os.Getenv("IS_PROD") != "true" {
		app.HandleDir("/docs", "./static/swagger-ui", iris.DirOptions{})
	}
	if os.Getenv("APP_DEBUG")=="true"{
		app.Logger().Level = golog.DebugLevel
	}

	// 构建路由
	router.Run(app)
	common.RegisterNormalTimeDecoder()

	// 启动应用
	app.Run(iris.Addr(":"+os.Getenv("PORT")), iris.WithConfiguration(iris.TOML("./configs/iris.tml")))

}
